package com.bensonbasement.snorflux.client.states;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;

import com.bensonbasement.snorflux.client.SnorfluxClient;
import com.bensonbasement.snorflux.client.VerbsPane;
import com.bensonbasement.snorflux.commands.Command;
import com.bensonbasement.snorflux.commands.TargetMap;
import com.bensonbasement.snorflux.commands.VerbInfo;
import com.bensonbasement.snorflux.messages.fromclient.CommandResponseMessage;
import com.bensonbasement.snorflux.messages.fromserver.CommandRequestMessage;
import com.bensonbasement.snorflux.messages.fromserver.WorldTimeMessage;
import com.bensonbasement.snorflux.utils.Direction;

public class CommandSelectState extends ConnectedState {
	
//	private final RBigEntity actor;
	private final CommandRequestMessage request;
	private VerbsPane verbsPane;
	
	public CommandSelectState(SnorfluxClient client, CommandRequestMessage request) {
		super(client);
		this.request = request;
//		actor = (RBigEntity) getMemory().getWorld().getWorldElement(request.getActorID());
	}
	
	@Override
	public void initialize() {
		super.initialize();
		verbsPane = new VerbsPane(request,this);
		client.getGamePanel().add(verbsPane,BorderLayout.EAST);
		client.getGamePanel().revalidate();
		//getMapPanel().repaint();
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		int keyCode = e.getKeyCode();
		if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {
			moveCommand(Direction.NORTH);
		}
		else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) {
			moveCommand(Direction.SOUTH);
		}
		else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {
			moveCommand(Direction.WEST);
		}
		else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {
			moveCommand(Direction.EAST);
		}
		else if (keyCode == KeyEvent.VK_SPACE) {
			// End turn
			endTurnChosen();
		}
		else {
			super.keyPressed(e);
		}
	}
	
	@Override
	public void handleWorldTimeMessage(WorldTimeMessage message) {
		throw new RuntimeException("Should not receive WorldTimeMessages while selecting a command.");
	}
	
	public void verbChosen(VerbInfo verb) {
		TargetMap targets = new TargetMap();
		// TODO: Add support for targets.
		Command command = new Command(verb.getName(),verb.getObjectID(),targets);
		sendCommand(command);
	}
	
	public void endTurnChosen() {
		sendCommand(null);
	}
	
	private void moveCommand(Direction dir) {
		VerbInfo moveVerb = request.getMoveVerb();
		TargetMap targets = new TargetMap();
		targets.setDirectionTarget("direction", dir);
		Command command = new Command(moveVerb.getName(),null,targets);
		sendCommand(command);
	}
	
	private void sendCommand(Command command) {
		CommandResponseMessage message = new CommandResponseMessage(command);
		sendMessage(message);
		client.getGamePanel().remove(verbsPane);
		client.getGamePanel().revalidate();
		changeState(new IdleState(client));
	}
}
